<template>
  <div>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
      class="demo-ruleForm" :size="formSize" status-icon>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客源来源" prop="passenger">
            <el-select v-model="ruleForm.passenger" placeholder="请选择">
              <el-option v-for="item in passengerlist" :key="item.Id" :label="item.Value" :value="item.Id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单来源" prop="orderSource">
            <el-select v-model="ruleForm.orderSource" placeholder="请选择">
              <el-option v-for="item in ordersourcelist" :key="item.Id" :label="item.Value" :value="item.Id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="container">
        <el-component> <el-form-item label="预定姓名" prop="truename">
            <el-input v-model="ruleForm.truename" />
          </el-form-item></el-component>
        <el-component>
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="ruleForm.phone" />
          </el-form-item></el-component>
        <el-component>
          <el-form-item label="预订单号" prop="reserVation">
            <el-input v-model="ruleForm.reserVation" />
          </el-form-item></el-component>
        <el-button type="success" @click="snow()">获取</el-button>
      </div>
      <div class="time">
        <el-component>
          <el-form-item label="入住日期" required>
            <el-col :span="24">
              <el-form-item prop="checkTime">
                <el-date-picker v-model="ruleForm.checkTime" type="date" placeholder="入住日期" style="width: 100%"
                  :disabled-date="disabledDate" @change="calculateDays" />
              </el-form-item>
            </el-col>
          </el-form-item>
        </el-component>
        <el-component> <el-form-item label="离店日期" required>
            <el-col :span="24">
              <el-form-item prop="departureTime">
                <el-date-picker v-model="ruleForm.departureTime" type="date" placeholder="离店日期" style="width: 100%"
                  :disabled-date="disabledDates" @change="calculateDays" />
              </el-form-item>
            </el-col>
          </el-form-item></el-component>
        <el-component>
          <el-form-item label="入住天数" prop="numBerday">
            <el-input v-model="ruleForm.numBerday" readonly="true" />
          </el-form-item>
        </el-component>
      </div>
      <el-form-item label="选择房型" :model="ruleForm.rtid" :rules="rules" ref="formRef" style="width: 1000px">
        <el-table :data="tableData">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="Rtname" label="房型名称" width="120" />
          <el-table-column prop="RoomApartment" label="可定数" width="120" />
          <el-table-column prop="Rprice" label="房价均价" width="120" />
          <el-table-column label="房间数量" width="120">
            <template v-slot="{ row }">
              <el-input v-model="row.roomCount" placeholder="请输入房间数量"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="">
            <template #default="scope">
              <el-button @click="openDialog(scope.row)" type="primary">
                排房
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-dialog v-model="dialogFormVisible" title="排房" width="500" @open="resetSelectedRooms">
        房间信息
        <br>
        <br>
        房型:{{ rooms.Rtname }}
        <br>
        未排房房间数量:{{ formRef.Count }}
        <br>
        <br>
        已排房间:
        <br>
        <span v-for="(roomNumber, index) in selectedRooms" :key="index">{{ roomNumber }}</span>
        <br>
        选择房号:
        <br>
        <div>
          <el-button v-for="(button, index) in buttons" :key="index" :class="{ 'is-active': button.isActive }"
            @click="toggleButton(button)">
            {{ button.RoomNumber }}
          </el-button>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="dialogFormVisible = false">
              完成
            </el-button>
          </div>
        </template>
      </el-dialog>
      <el-form-item label="备注" prop="desc">
        <el-input v-model="ruleForm.remark" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
//axios.defaults.baseURL = 'http://10.31.59.9:9033/api/';//设置请求的根路径
import axios from 'axios';
interface RuleForm {
  truename: string
  orderSource: string//订单来源
  checkTime: string
  departureTime: string
  remark: string
  passenger: string//客源来源
  phone: string
  reserVation: string
  numBerday: number
  roomid: number,
  roomNumber: number,
  tenantId: 'zhansgan'
  rsid: 2,
  msId: 1,
  rtid: number,
}
import router from '@/router';
import { onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { number } from 'echarts';
import { Row } from 'element-plus/es/components/table-v2/src/components/index.mjs';
const tableData = ref([{ roomCount: 0, /* 其他数据 */ }])
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const dialogFormVisible = ref(false)
const buttons = ref([{ RoomNumber: String ,RoomId:number}
]);
const selectedRooms = ref([]);
const button = ref({ isActive: false });  // 用于记录当前选中的按钮
const formRef = ref([{ Count: 0 }]);
const rooms = ref([]);
const ruleForm = reactive<RuleForm>({
  truename: '',//预定姓名
  orderSource: '',//订单来源
  checkTime: '',  //预定时间
  departureTime: '',  //离店时间
  remark: '',  //备注
  phone: '',//手机号码  
  passenger: '',//客源来源
  reserVation: '',//单号
  numBerday: 0,//入住天数
  roomid: 0, //房间id
  roomNumber: 0,//预订房间数量
  tenantId: 'zhansgan',//租户id
  rsid: 2,//房态筛选ID 
  msId: 1,//更多筛选ID
 rtid:0, //房型id
 roomNumberName: "",
  rtname: "",
  passengerName: "",
  State:62,

})
const ordersourcelist = ref([{ Id: Number, Value: String }]);
const passengerlist = ref([{ Id: Number, Value: String }]);
const rules = reactive<FormRules<RuleForm>>({
  truename: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]+$/, message: '姓名格式有误' },
    { min: 2, message: '姓名格式有误', trigger: 'blur' },
  ],
  numBerday:
    [
      { required: true, message: '请输入入住天数', trigger: 'blur' },
      { pattern: /^\d+$/, message: '天数输入有误', trigger: 'blur' },
    ],
  reserVation:
    [
      { required: true, message: '请输入订单号', trigger: 'blur' },
    ],
  orderSource:
    [
      {
        required: true,
        message: '请选择订单来源',
        trigger: 'change',
      },
    ],
  passenger: [
    {
      required: true,
      message: '请选择客源来源',
      trigger: 'change',
    }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码' }
  ],
  checkTime: [
    { required: true, message: '请输入住日期', trigger: 'blur' },
  ],
  departureTime: [
    { required: true, message: '请输离店日期', trigger: 'blur' },
  ],
})
//禁用之前日期
const disabledDate = (time: Date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 将今天的时间部分清零，以便只比较日期部分  
  return time.getTime() < today.getTime();
};

const disabledDates = (time: Date) => {
  const currentDate = new Date();
  return time.getTime() < currentDate.getTime();
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  ruleForm.roomid = button.value.RoomId;
  ruleForm.roomNumber = rooms.value.roomCount;
  ruleForm.rtid = rooms.value.Rtid;

  await formEl.validate((valid, fields) => { 
    if (valid) {
      axios.post(`http:localhost:5003/api/ClientcuStomer/AddClientcu`,ruleForm).then(res => {
        if (res.data.Code == 200) {
          ElMessage.success("办理成功");
        
    router.push({ path: '/index/subIndex/RoomList' })

        } else {
          ElMessage.error("办理失败");
          return;
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
//点击排房都会清空已选房间
const openDialog = (row) => {
  const roomCount = row.roomCount;
  const id = row.Rtid;
  rooms.value = row;
  
  if (roomCount == 0) {
    ElMessage.error('房间数量不能为0');
    return;
  }
  if (roomCount == null) {
    ElMessage.error('房间数量不能为空');
    return;
  }
  if (!/^[1-9]\d*$/.test(roomCount)) {
    ElMessage.error('房间数量输入格式有误');
    return;
  }
  if (row.roomCount > row.RoomApartment) {
    ElMessage.error('房间数量不能大于可定数');
    return;
  }
  dialogFormVisible.value = true; // 打开弹出框 
  axios.get(`http:localhost:5003/api/ClientcuStomer/RoomNumShow?id=${id}`).then(res => {
    buttons.value = res.data;
    button.value=buttons.value[0];
  })
  axios.get("http:localhost:5003/api/ClientcuStomer/RoomShow").then(res => {
  })
};
const snow = () => {
  axios.get("http:localhost:5003/api/ClientcuStomer/SnowIdWithTimestamp").then(res => {
    ruleForm.reserVation = res.data
  })
}
const resetSelectedRooms = () => {
  selectedRooms.value = [];
};
const toggleButton = (button) => {
  button.isActive = !button.isActive;

  if (button.isActive) {
    selectedRooms.value.push(button.RoomNumber);
    formRef.value.Count = rooms.value.roomCount;
    formRef.value.Count -= 1;
  } else {
    const index = selectedRooms.value.indexOf(button.RoomNumber);
    if (index !== -1) {
      selectedRooms.value.splice(index, 1);
      formRef.value.Count += 1;
    }
  }
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
function RoomShow() {
  axios.get("http:localhost:5003/api/ClientcuStomer/RoomShow").then(res => {
    tableData.value = res.data
  })
}
function orderstatusShow() {
  axios
    .get("http:localhost:5003/api/Dic/DicShow?Identification=passenger")
    .then((res) => {
      passengerlist.value = res.data;
    });
}
function calculateDays() {
  const checkTime = new Date(ruleForm.checkTime);
  const departureTime = new Date(ruleForm.departureTime);
  const diffTime = departureTime.getTime() - checkTime.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 3600 * 24));
  ruleForm.numBerday = diffDays;
}
function ordersourceShow() {
  axios
    .get("http:localhost:5003/api/Dic/DicShow?Identification=ordersource")
    .then((res) => {
      ordersourcelist.value = res.data;
    });
}
onMounted(() => {
  ordersourceShow();
  orderstatusShow();
  RoomShow();
});
</script>
<style>
.container {
  display: flex;
  justify-content: space-between;
  /* 根据需要调整间距 */
}

.container>* {
  flex-shrink: 0;
  /* 允许组件缩小 */
}

.time {
  display: flex;
  justify-content: space-between;
  /* 根据需要调整间距 */
}

.time>* {
  flex-shrink: 0;
  /* 允许组件缩小 */
}
</style>